package main

import (
	"strconv"
	"time"
	"github.com/codeskyblue/go-sh"
)

func DoMonitor(){
	monitorList := GetAllMonitorList()
	for _, monitor := range monitorList {
		go runMonitor(monitor)
	}
}

//执行定时脚本
func runMonitor(monitor map[string]string) bool{

	miniteTime := time.Now().Minute()

	frequency,_ := strconv.Atoi(monitor["frequency"])

	if miniteTime % frequency != 0 {
		return false;
	}

	var JobTimeOut int64 = 120
	//加锁
	Lock := JobLock(monitor["id"],JobTimeOut,"Monitor")

	if Lock ==  0{
		return false;
	}


	//执行脚本
	monitorResult := runMonitorJob(monitor)

	JobUnLock(monitor["id"],Lock,"Monitor")

	if monitorResult != "success"{
		monitorJobAlarms := getMonitorJobAlarmsByMonitorId(monitor["id"])
		if 0 == len(monitorJobAlarms){
			return false
		}

		message := monitor["id"]+monitor["monitor_name"]+"异常"
		monitorJobAlarmMessage := getMonitorJobAlarmMessageByMonitorId(monitor["id"])
		if monitorJobAlarmMessage["message"] != ""{
			message = monitorJobAlarmMessage["message"]
		}


		for _,monitorJobAlarm := range monitorJobAlarms{
			sendMessage(monitorJobAlarm["phone_code"],message)
		}
	}

	return true
}

//执行脚本方法
func runMonitorJob(monitor map[string]string) string{
	//运行
	session := sh.NewSession()
	session.SetDir("/")
	output,_ := session.Command("curl", monitor["monitor_api"]).Output()

	return string(output)
}
